package com.example.demo.db;

import com.alibaba.druid.pool.DruidDataSource;
import com.example.demo.db.properties.MysqlDruidProperties;
import com.example.demo.util.ApplicationContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.core.ApplicationContext;
import org.springframework.beans.BeanUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import javax.sql.DataSource;
import java.sql.DriverManager;
import java.util.Map;

/**
 * @author Hyman.huang
 * @create 2023-07-14-9:05
 */
@Slf4j
@EnableConfigurationProperties(MysqlDruidProperties.class)
public class DynamicDataSource extends AbstractRoutingDataSource {
    public static Map<Object, Object> dynamicTargetDataSources;

    @Override
    protected Object determineCurrentLookupKey() {
        String dataSource = DynamicDataSourceHandler.getDataSource();
        System.out.println(Thread.currentThread().getName()+"dataSource:"+dataSource);
        return dataSource;
    }

    @Override
    public void setTargetDataSources(Map<Object, Object> targetDataSources) {
        super.setTargetDataSources(targetDataSources);
        this.dynamicTargetDataSources = targetDataSources;
    }

    // 创建数据源
    public boolean createDataSource(String url, String username, String password,String dbType) {
        try {
            DruidDataSource druidDataSource = new DruidDataSource();
            if("mysql".equals(dbType)){
                BeanUtils.copyProperties(ApplicationContextUtils.getBean("mysqlDruidProperties"), druidDataSource);
            }else if("orcale".equals(dbType)){

            } else if ("sqlserver".equals(dbType)) {

            } else {
                throw new Exception("dbType错误！");
            }
            druidDataSource.setUrl(url);
            druidDataSource.setUsername(username);
            druidDataSource.setPassword(password);

            DataSource createDataSource = druidDataSource;
            druidDataSource.init();
            Map<Object, Object> dynamicTargetDataSources_temp = this.dynamicTargetDataSources;
            dynamicTargetDataSources_temp.put(url, createDataSource);// 加入map
            setTargetDataSources(dynamicTargetDataSources_temp);// 将map赋值给父类的TargetDataSources
            super.afterPropertiesSet();// 将TargetDataSources中的连接信息放入resolvedDataSources管理
            log.info(url + "数据源初始化成功");
            return true;
        } catch (Exception e) {
            log.error(e + "");
            return false;
        }
    }


}
